package com.hailong.zyt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hailong.zyt.beans.Homework;
import com.hailong.zyt.beans.HomeworkStudent;
import com.hailong.zyt.beans.Student;
import com.hailong.zyt.config.PageConfig;
import com.hailong.zyt.mapper.HomeworkMapper;
import com.hailong.zyt.mapper.HomeworkStudentMapper;
import com.hailong.zyt.mapper.StudentMapper;
import com.hailong.zyt.service.HomeworkStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hailong.zyt.utils.FileUploadUtil;
import com.hailong.zyt.utils.FileUtil;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hailong
 * @since 2021-06-01
 */
@Service
public class HomeworkStudentServiceImpl extends ServiceImpl<HomeworkStudentMapper, HomeworkStudent> implements HomeworkStudentService {

    private HomeworkStudentMapper homeworkStudentMapper;
    private HomeworkMapper homeworkMapper;
    private StudentMapper studentMapper;

    @Override
    public IPage<HomeworkStudent> getStudentHomeworkByHwId(Integer nowPage, Long hwId) {
        QueryWrapper<HomeworkStudent> wrapper = new QueryWrapper<>();
        wrapper.eq("hw_id", hwId);
        Page<HomeworkStudent> hPage = new Page<>(nowPage, PageConfig.PAGESIZE);
        IPage<HomeworkStudent> hwsPage = homeworkStudentMapper.selectPage(hPage, wrapper);

        //查询学生和作业信息
        for(HomeworkStudent homeworkStudent : hwsPage.getRecords()) {
            homeworkStudent.setStudent(studentMapper.selectById(homeworkStudent.getStuId()));
            homeworkStudent.setHomework(homeworkMapper.selectById(homeworkStudent.getHwId()));
        }
        return hwsPage;
    }

    @Override
    public HomeworkStudent getOneHomework(Long hwId, Long stuId) {
        Map<String, Object> map = new HashMap<>();
        map.put("hw_id", hwId);
        map.put("stu_id", stuId);
        QueryWrapper<HomeworkStudent> wrapper = new QueryWrapper<>();
        wrapper.allEq(map);
        HomeworkStudent homework = this.getOne(wrapper);
        if (homework == null) return null;
        Homework hw = homeworkMapper.selectById(homework.getHwId());
        if(hw != null) {
            LocalDateTime now = LocalDateTime.now();
            if(now.isBefore(hw.getHwStartTime()) || now.isAfter(hw.getHwEndTime())) {
                homework.setHwsState(2);
                this.update(homework, new UpdateWrapper<HomeworkStudent>().allEq(map));
            }
            homework.setHomework(hw);
        }
        return homework;
    }

    @Override
    public int saveHomework(HomeworkStudent homeworkStudent, Model model) {
        Map<String, Object> map = new HashMap<>();
        map.put("hw_id", homeworkStudent.getHwId());
        map.put("stu_id", homeworkStudent.getStuId());
        this.update(homeworkStudent, new UpdateWrapper<HomeworkStudent>().allEq(map));
        return 0;
    }

    @Override
    public int submitHomework(HomeworkStudent homework, Student student, MultipartFile file) throws IOException {
        HomeworkStudent oldHomework = this.getOneHomework(homework.getHwId(), student.getStuId());
        //如果原来有文件，且现在传入新文件，删除原来
        if(oldHomework != null && oldHomework.getHwsFileName() != null && !file.isEmpty()) {
            FileUtil.deleteFile(oldHomework.getHwsFileName());
        }
        if(!file.isEmpty()) {
            //上传新文件
            String dir = FileUploadUtil.ROOT_FILE + student.getStuId();
            String fileLocation = FileUploadUtil.upload(dir, file);
            homework.setHwsFileName(fileLocation);
        }

        homework.setStuId(student.getStuId());
        Map<String, Object> map = new HashMap<>();
        map.put("hw_id", homework.getHwId());
        map.put("stu_id", student.getStuId());
        if(oldHomework == null) this.save(homework);
        else this.saveOrUpdate(homework);
        return 0;
    }

    @Override
    public List<Student> getStudentNotFinished(Long hwId) {
        return studentMapper.selectStudentsNotFinished(hwId);
    }

    @Override
    public void downloadFile(String fileName, HttpServletResponse response) throws IOException {
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");        //这边可以设置文件下载时的名字，我这边用的是文件原本的名字，可以根据实际场景设置
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(FileUploadUtil.getFileNameFromPath(fileName), "UTF-8"));
        FileUtil.writeBytes(fileName, response.getOutputStream());
    }

    @Override
    public Integer getHomeworkState(Long hwId, Long stuId) {
        HomeworkStudent homework = this.getOneHomework(hwId, stuId);
        if(homework == null) return -1;
        else return homework.getHwsState();
    }

    @Autowired
    public void setHomeworkStudentMapper(HomeworkStudentMapper homeworkStudentMapper) {
        this.homeworkStudentMapper = homeworkStudentMapper;
    }

    @Autowired
    public void setHomeworkMapper(HomeworkMapper homeworkMapper) {
        this.homeworkMapper = homeworkMapper;
    }

    @Autowired
    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }
}
